/* Copyright 2012 Tobias Marschall
 *
 * This file is part of CLEVER.
 *
 * CLEVER is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CLEVER is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with CLEVER.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <sstream>

#include "FastqReader.h"

using namespace std;

FastqReader::FastqReader(boost::iostreams::filtering_istream& in, bool remove_trailing_number) : in(in), next(0), line_nr(0), remove_trailing_number(remove_trailing_number) {
	readNext();
}

void FastqReader::readNext() {
	std::string line;
	int n = 0;
	next = std::auto_ptr<fastq_record_t>(0);
	std::string name = "";
	std::string seq = "";
	std::string qual = "";
	try {
		while (std::getline(in,line)) {
			line_nr += 1;
			// strip line from leading or trailing whitespaces
			size_t start = line.find_first_not_of(" \t\r\n");
			size_t end = line.find_last_not_of(" \t\r\n");
			line = line.substr(start, end-start+1);
			if (line.size() == 0) throw std::runtime_error("");
			n += 1;
			if (n == 1) {
				if (line[0] != '@') throw std::runtime_error("");
				size_t cut_pos = line.find(' ');
				if (remove_trailing_number) {
					if (cut_pos == string::npos) {
						if ((line.size() > 3) && (line[line.size()-2] == '/') && (line[line.size()-1] >= '0') && (line[line.size()-1] <= '9')) {
							cut_pos = line.size()-2;
						}
					} else {
						if ((cut_pos > 3) && (line[cut_pos-2] == '/') && (line[cut_pos-1] >= '0') && (line[cut_pos-1] <= '9')) {
							cut_pos -= 2;
						}
					}
					
				}
				if (cut_pos == string::npos) {
					name = line.substr(1);
				} else {
					name = line.substr(1, cut_pos - 1);
				}
			} else if (n == 2) {
				seq = line;
			} else if (n == 3) {
				if (line.compare("+") != 0) {
					std::ostringstream oss;
					oss << '+' << name;
					if (line.substr(0,oss.str().size()).compare(oss.str()) != 0) throw std::runtime_error("");
				}
			} else if (n == 4) {
				qual = line;
				if (qual.size() != seq.size()) throw std::runtime_error("");
				next = std::auto_ptr<fastq_record_t>(new fastq_record_t(name, seq, qual));
				break;
			}
		}
	} catch (std::runtime_error&) {
		std::ostringstream oss;
		oss << "Error parsing FASTQ input. Offending line: " << line_nr << ": \"" << line << "\"";
		throw std::runtime_error(oss.str());
	}
}

bool FastqReader::hasNext() const {
	return next.get() != 0;
}

auto_ptr<FastqReader::fastq_record_t> FastqReader::getNext() {
	auto_ptr<fastq_record_t> result = next;
	readNext();
	return result;
}

